const path = require('path');
const WebpackBar = require('webpackbar');
const CompressionWebpackPlugin = require('compression-webpack-plugin');

// const { version, author } = require('./package.json');
const { isProdEnv, isDevEnv, devPort } = require('./src/config/settings.js');

const resolve = dir => {
  return path.join(__dirname, dir);
};

const injectProdConfig = config => {
  // 不使用source-map
  config.devtool('none');
  //压缩代码
  config
    .plugin('compression')
    .use(CompressionWebpackPlugin, [
      {
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + ['html', 'js', 'css', 'svg'].join('|') + ')$'),
        threshold: 8192,
        minRatio: 0.8
      }
    ])
    .end();
  // 更好的利用缓存，打包的app.xxx.js不会因为内部chunk的改变而改变
  config.optimization.runtimeChunk('single');
};

const injectDevConfig = config => {
  config.devtool('cheap-module-eval-source-map');
};

module.exports = {
  publicPath: '',
  assetsDir: 'static', // 放置打包的静态文件目录
  outputDir: 'dist', // 打包的目录
  lintOnSave: isDevEnv, // 开发环境，保存时进行eslint检查
  devServer: {
    hot: true,
    port: devPort,
    open: true,
    noInfo: false,
    overlay: {
      warnings: true,
      errors: true
    }
    // after: isDevEnv ? require('./mock/mock-server.js') : '',
  },
  // 默认不开启运行时编译可以减小体积且速度更快（除vue文件外，不能使用template模板，只能使用render函数）
  runtimeCompiler: false,
  productionSourceMap: false, // 生产环境不需要 source map
  // 默认共有配置
  configureWebpack() {
    const devtool = isDevEnv ? 'source-map' : 'none';
    return {
      devtool,
      // runtimeCompiler: true,
      // productionSourceMap: false,
      resolve: {
        alias: {
          '@': resolve('src')
        }
      },
      plugins: [
        new WebpackBar() // webpack启动时显示进度
      ],
      // 可以减少嵌套，减少打包体积
      optimization: {
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            elementUI: {
              name: 'chunk-elementUI',
              priority: 20,
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/
            },
            commons: {
              name: 'chunk-commons',
              test: resolve('src/components'),
              minChunks: 3,
              priority: 5,
              reuseExistingChunk: true
            }
          }
        }
      }
    };
  },
  // 针对不同环境的配置
  // chainWebpack会比configureWebpack先调用
  chainWebpack(config) {
    // 生产环境独有的配置
    config.when(isProdEnv, injectProdConfig);
    // 开发环境独有的配置
    config.when(isDevEnv, injectDevConfig);
  },
  css: {
    requireModuleExtension: true, // 必须被显式地指定为true，才能将将自定义配置应用到 CSS 文件中
    sourceMap: true,
    // 向相关的 loader 传递选项
    loaderOptions: {
      scss: {
        additionalData: '@import "~@/styles/global.scss";' // 提前载入
      }
    }
  }
};
